const { app, ipcMain } = require("electron");
const path = require("path");
const StorageAdapter = require("./StorageAdapter");
const { spawn } = require("child_process");
//读取配置password clickPos
const _CONFIG = new StorageAdapter(path.join(__dirname, "../../data/config.json"))
const CONFIG = _CONFIG.read()

//注入页面和逻辑
function inJs(width, height, _html, config) {
    console.log("inJs");
    //加载页面
    const ipcRenderer = window.electron;
    let _SignOutBox = document.createElement("div");
    _SignOutBox.className = "SignOutBox";
    _SignOutBox.innerHTML = _html;
    document.body.appendChild(_SignOutBox);
    let pos = Object.assign([], ["top", "left", 100, 5], config.clickPos ? config.clickPos.split(" ") : []);
    let clickCount = 0,
        timer;
    document.body.onclick = (e) => {
        clearTimeout(timer);
        timer = setTimeout(() => {
            clickCount = 0;
        }, 500);
        //连点指定位置出现弹窗
        if (pos[0] === "top" && e.pageY > Number(pos[2]))
            return (clickCount = 0);
        if (pos[0] === "bottom" && e.pageY < height - Number(pos[2]))
            return (clickCount = 0);
        if (pos[1] === "left" && e.pageX > Number(pos[2]))
            return (clickCount = 0);
        if (pos[1] === "right" && e.pageX < width - Number(pos[2]))
            return (clickCount = 0);
        clickCount++;
        if (clickCount >= pos[3]) {
            clickCount = 0;
            _SignOutBox.style.display = "flex";
            _SignOutBox.click();
        }
    };

    const list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
    let buttonDom = "";
    for (var i = 0; i < list.length; i++)
        buttonDom +=
            '<div class="button" data-value="' +
            list[i] +
            '">' +
            list[i] +
            "</div>";
    buttonDom += `<div class="button">
        <svg width="55" height="34" style="transform:scale(.9)">
            <path d="M15,2 L53,2 L53,32 L15,32 L2,17Z" fill="none" stroke="currentColor" stroke-width="2"></path>
            <g style="transform-origin:30px 20px; transform: scale(.8);">
                <line x1="25" y1="8" x2="45" y2="26" stroke="currentColor" stroke-width="2"></line>
                <line x1="45" y1="8" x2="25" y2="26" stroke="currentColor" stroke-width="2"></line>
            </g>
        </svg>
    </div>`;
    const _buttonBox = _SignOutBox.querySelector(".s-btn>div"),
        _input = _SignOutBox.querySelector("input");
    _buttonBox.innerHTML = buttonDom;
    let value = [];
    _buttonBox.onclick = (e) => {
        let _value =
            e.target.className.toLocaleLowerCase() === "button"
                ? e.target.getAttribute("data-value") || -1
                : false;
        if (!_value) return false;
        if (_value === -1) {
            value.pop();
        } else {
            value.push(_value);
        }
        _input.value = value.join("");
    };
    const _message = _SignOutBox.querySelector(".s-msg");
    const _configEle = _SignOutBox.querySelector('.s-setting')
    const _textarea = _configEle.querySelector('.s-textarea')
    const _quitEle = _SignOutBox.querySelector('.s-quit')
    // 配置
    let _textareaHtml = (key, value) => {
        if (typeof value === 'object') {
            for (let i in value) _textareaHtml(key + '-' + i, value[i])
            return
        }
        if (config.canWrite[key]) _textarea.innerHTML += `<div class="fitem"><span>${config.canWrite[key]}</span><input type="text" value="${value}" name="${key}" /></div>`
    }
    if (config.canWrite) for (let i in config) _textareaHtml(i, config[i])
    let clicker, initer,
        init = () => {
            clearTimeout(clicker);
            clearTimeout(initer);
            _input.value = "";
            value = [];
            _message.innerHTML = "";
            _SignOutBox.style.display = "none";
            _configEle.style.display = 'none'
            _quitEle.style.display = 'block'
        },
        autoClear = () => {
            console.log("10s after clear");
            clearTimeout(clicker);
            clicker = setTimeout(init, 30000);
        };
    let swsetting = _SignOutBox.querySelector(".sw-setting")
    if (swsetting) swsetting.onclick = (e) => {
        _configEle.style.display = 'block'
        _quitEle.style.display = 'none'
        e.stopPropagation();
    };
    _SignOutBox.querySelector(".sw-quit").onclick = (e) => {
        _configEle.style.display = 'none'
        _quitEle.style.display = 'block'
        e.stopPropagation();
    };
    _SignOutBox.querySelector(".s-cancel").onclick = (e) => {
        e.stopPropagation();
        init();
    };
    _SignOutBox.querySelector(".s-keyword").onclick = (e) => {
        e.stopPropagation();
        ipcRenderer.send('osk')
    };
    _SignOutBox.querySelector(".sure-setting").onclick = (e) => {
        e.stopPropagation();
        let inputEle = _textarea.querySelectorAll('input')
        let _setValue = (name, value, option) => {
            if (name.length === 1) {
                option[name[0]] = value
            } else {
                if (!option[name[0]]) option[name[0]] = {}
                _setValue(name.slice(1), value, option[name[0]])
            }
        }
        for (let i = 0; i < inputEle.length; i++) {
            _setValue(inputEle[i].name.split('-'), inputEle[i].value, config)
        }
        ipcRenderer.send('s-config', config)
    };
    let passWord;
    ipcRenderer.send("passWord");
    ipcRenderer.on("passWord", (d) => (passWord = d));
    _SignOutBox.querySelector(".sure-quit").onclick = () => {
        let password = _input.value;
        clearTimeout(initer);
        if (password - passWord === 0) return ipcRenderer.send("signOut");
        _message.innerHTML = "密码错误";
        initer = setTimeout(function () {
            _message.innerHTML = "";
        }, 3000);
    };
    _SignOutBox.onclick = autoClear;
}
const SignOut = {
    in: (win) => {
        //创建页面文件
        SignOut.win = win;
        let { width, height } = win.getContentBounds();
        win.webContents.on("did-finish-load", () => {
            // 注入css html
            win.webContents.insertCSS(SignOut._css);
            win.webContents.executeJavaScript(
                `(${inJs.toString()})(${width},${height},\`${SignOut._html
                }\`,${JSON.stringify(CONFIG)})`
            );
        });
        ipcMain.on("signClear", (e) => e.reply("signClear"));
        ipcMain.on("signHide", () => win.webContents.send("signHide"));
        ipcMain.on("signOut", SignOut.out);
        ipcMain.on("s-config", (e, data) => {
            _CONFIG.write(data)
            app.relaunch()
            app.exit(0)
        });
        ipcMain.on("passWord", (e) => {
            win.webContents.send("passWord", CONFIG.password || "123");
        });
        ipcMain.on("osk", (e) => {
            spawn('cmd.exe', ['/s', '/c', 'osk'])
        });
    },
    out: () => {
        if (SignOut.win) {
            SignOut.win.hide();
        }
        setTimeout(function () {
            app.quit();
        }, 100);
    },
    _css: `
        html,body{user-select:none}
        .SignOutBox{width: 100%; height: 100%;position: absolute;top:0;left:0;background:#00000060;z-index:1000;display:none;text-align: center;font-size: 26px;color: #333333;line-height: 48px;font-family: '微软雅黑';align-items:center;justify-content:center;}
        .SignOutBox::-webkit-scrollbar { display: none; }
        .SignOutBox .s-box {width: 650px;background-color: #ececec;border-radius: 6px;}
        .SignOutBox .s-hd {width: 100%;border-bottom: 1px solid #c9c9c9;line-height: 60px;}
        .SignOutBox .s-msg {width: 100%;height: 40px;color: red;line-height: 40px;}
        .SignOutBox .s-bd {padding: 0px 60px 20px;}
        .SignOutBox  input {height: 48px;width: 100%;padding: 0 10px;font-size: 20px;font-family: '微软雅黑';border: none;box-sizing:border-box}
        .SignOutBox  input::-webkit-input-placeholder {color: #999;}
        .SignOutBox .s-btn {margin: 15px 0;padding: 5px;background: #c9c9c9;border-radius: 5px;position: relative;}
        .SignOutBox .s-btn::before {content: '';width: 0;height: 0;border: 10px solid transparent;border-bottom-color: #c9c9c9;position: absolute;top: -18px;left: 30px;}
        .SignOutBox .s-btn>div {border-radius: 5px;background-color: #ececec;display: flex;flex-wrap: wrap;padding: 5px;}
        .SignOutBox .button {width: 75px;height: 50px;margin: 5px;border-radius: 4px;background-color: white;}
        .SignOutBox .button:last-child {width: 160px;box-sizing:border-box;padding:8px;font-size:0}
        .SignOutBox .button svg {pointer-events:none}
        .SignOutBox .s-footer {display: flex;justify-content: center;padding: 0 80px 20px;}
        .SignOutBox .s-footer>div { border-radius: 5px;font-size: 20px;margin:0 15px;padding: 0 20px;}
        .SignOutBox .s-footer>div:nth-child(3) {border: 1px solid #ccc;color: #333;}
        .SignOutBox .s-footer>div:nth-child(1) {border: 1px solid #027aff;color: #027aff;}
        .SignOutBox .s-footer>div:nth-child(2) {background: #027aff;color: white; }
        .SignOutBox .s-setting{display:none;}
        .SignOutBox .s-textarea{height:240px;line-height:25px;overflow-y:auto;font-size:20px;padding:0 20px;margin-bottom:30px;}
        .SignOutBox .s-textarea::-webkit-scrollbar { display: none; }
        .SignOutBox .s-textarea input{height:40px;line-height:40px;background:#f8f8f8;}
        .SignOutBox .s-textarea .fitem{position:relative;padding-left:150px;margin-bottom:10px;}
        .SignOutBox .s-textarea .fitem span{position:absolute;top:0;left:0;width:140px;text-align:right;line-height:20px; height:40px; display:flex;align-items:center;justify-content:center; color:#999}
    `,
    _html: `
        <div class="s-box">
            <div class="s-hd">管理员操作</div>
            <div class="s-quit">
            <div class="s-msg"></div>
            <div class="s-bd">
                    <input type="text" placeholder="请输入管理员密码">
                    <div class="s-btn">
                        <div></div>
                    </div>
                </div>
                <div class="s-footer">
                    <div class="s-cancel">取消</div>
                    <div class="sure-quit">确认退出</div>
                    ${CONFIG.canWrite ? `<div class="sw-setting">软件配置</div>` : ""}
                </div>
            </div>
            <div class="s-setting">
                <div style="color:orange;font-size:20px;">修改配置请参考软件说明，慎重！</div>
                <div class="s-textarea">
                </div>
                <div class="s-footer"> 
                    <div class="sw-quit">返回</div>
                    <div class="sure-setting">确认配置</div>
                    <div class="s-keyword">虚拟键盘</div>
                </div>
            </div>
        </div>
    `,
};
module.exports = SignOut;
